package com.yl.immodule.widget;

import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.yl.immodule.R;
import com.hm.poc.chat.ChatMessageCategory;
import com.hm.poc.chat.ChatMessageStatus;
import com.unionbroad.greendao.ChatMessage;
import com.yl.immodule.v.models.ChatMessageViewModel;

import java.util.function.Function;


public class ChatMessageContainer extends RelativeLayout {
    private static final String TAG = "ChatMessageContainer";
    private ChatMessageViewModel mViewModel;
    public ChatMessageContainer(Context context, AttributeSet attrs) {
        super(context, attrs);
        setClickable(true);
    }

    public void setViewModel(ChatMessageViewModel mViewModel) {
        this.mViewModel = mViewModel;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void bindChatContent(ChatMessage message) {
        removeAllViews();
        final boolean isOut = message.getIs_out();
        final int category = message.getCategory();
        
        // 记录重要信息，便于调试
        Log.d(TAG, "绑定内容: ID=" + message.getId() + ", isOut=" + isOut + ", 类型=" + category + ", 进度=" + message.getUpdown_progress());
        
        View item;
        switch (category) {
            case ChatMessageCategory.TEXT:
                item = LayoutInflater.from(getContext()).inflate(isOut ? R.layout.chat_right_textview : R.layout.chat_left_textview, null);
                ((TextView) item).setText(message.getText());
                break;
            case ChatMessageCategory.IMAGE:
                ImageMessageView imageView = new ImageMessageView(getContext());
                String localFile = message.getLocalFile();
                int progress = message.getUpdown_progress();
                
                Log.d(TAG, "绑定图片消息: ID=" + message.getId() + ", localFile =" + localFile + ", 进度=" + progress + ", isOut=" + isOut);
                
                // 检查图片文件是否存在
                if (localFile != null && !localFile.isEmpty()) {
                    imageView.loadImage(isOut,localFile, progress, new Function<String, Void>() {
                        @Override
                        public Void apply(String s) {
                            return null;
                        }
                    });
                } else if (message.getHttpFile() != null && !message.getHttpFile().isEmpty()) {
                    // 如果本地文件不存在但有网络URL，显示网络图片
                    imageView.loadImage(isOut,message.getHttpFile(), 100,new Function<String, Void>() {
                        @Override
                        public Void apply(String s) {
                            if (mViewModel != null){
                                message.setLocalFile(s);
                                Log.e(TAG, "下载成功保存: "+message.getLocalFile());
                                mViewModel.setChatMessageLocalPath(message);
                            }
                            return null;
                        }
                    });
                } else {
                    // 没有图片源，显示错误
                    imageView.setError("图片加载失败");
                }
                
                item = imageView;
                break;
            case ChatMessageCategory.VIDEO_FILE:
                // 处理视频消息

                message.getThumb_url();
                VideoFileCellLayout videoCell = (VideoFileCellLayout) LayoutInflater.from(getContext()).inflate(isOut ? R.layout.chat_right_video_file : R.layout.chat_left_video_file, null);
                videoCell.bindData(message);
                item = videoCell;
                
                Log.d(TAG, "绑定视频消息: ID=" + message.getId() + ", localFile =" + message.getLocalFile() + 
                        ", 进度=" + message.getUpdown_progress() + ", isOut=" + isOut);
                break;
            case ChatMessageCategory.AUDIO:
            case ChatMessageCategory.VIDEO:
            case ChatMessageCategory.AUDIO_PTT:
                item = LayoutInflater.from(getContext()).inflate(isOut ? R.layout.chat_right_audio_video_item : R.layout.chat_left_audio_video_item, null);
                TextView tv = (TextView) item.findViewById(R.id.text);
                ImageView iv = (ImageView) item.findViewById(R.id.icon);
                switch (category) {
                    case ChatMessageCategory.AUDIO:
                        tv.setText("语音呼叫");
                        iv.setImageResource(R.drawable.ic_dialer_sip_black_24dp);
                        break;
                    case ChatMessageCategory.VIDEO:
                        tv.setText("视频呼叫");
                        iv.setImageResource(R.drawable.ic_dialer_sip_black_24dp);
                        break;
                    case ChatMessageCategory.AUDIO_PTT:
                        tv.setText("对讲");
                        iv.setImageResource(R.drawable.ic_dialer_sip_black_24dp);
                        break;
                }
                Integer sip_status = message.getSip_status();
                if (sip_status != null) {
                    switch (sip_status) {
                        case ChatMessageStatus.Sip.CANCEL:
                            tv.setText("已取消");
                            break;
                        case ChatMessageStatus.Sip.UNRESPONSE:
                            tv.setText("未接听");
                            break;
                    }
                }
                break;
            case ChatMessageCategory.PTT_AUDIO_FILE:
            case ChatMessageCategory.AUDIO_FILE:
                AudioFileCellLayout audioCell = (AudioFileCellLayout) LayoutInflater.from(getContext()).
                        inflate(isOut ? R.layout.chat_right_audio_file : R.layout.chat_left_audio_file, null);
                audioCell.bindData(message);
                long len = message.getDuration() != null ? message.getDuration() : 0;
                int min = (int) (getResources().getDimension(R.dimen.chat_audiofile_cell_min_width));
                int max = (int) (getResources().getDimension(R.dimen.chat_audiofile_cell_max_width));
                int increase = (int) getResources().getDimension(R.dimen.chat_audiofile_cell_more);
                if (len > 60) {
                    len = 60;
                }
                if (len <= 3) {
                    increase = 0;
                } else if (len == 4) {
                    // default
                } else if (len <= 10) {
                    increase = (int) (increase * (len - 4));
                } else {
                    increase = (increase * (10 - 4)) + (int) ((len - 10) * (max - min) / 50);
                }

                LayoutParams p = (LayoutParams) audioCell.getLayoutParams();
                if (p == null) {
                    p = new LayoutParams(0, (int) getResources().getDimension(R.dimen.chat_message_min_heght));
                }
                p.width = min + increase;
                audioCell.setLayoutParams(p);
                //===============

                item = audioCell;
                break;
            default:
                TextView tips = new TextView(getContext());
                tips.setText("unsupport");
                item = tips;
                break;
        }

        if (item != null) {
            addView(item);
        }
    }
}
